package pers.wwz.study.redisson.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/redisson")
@Slf4j
public class RedissonController {

    @Autowired
    private StringRedisTemplate template;

    @Autowired
    private Redisson redisson;

    /**
     * 分布式锁测试
     * 说明1:锁超时时间是30s,如果获取锁30s还没主动释放锁,锁会过期;获取锁后redis中会存一个hash类型的key
     * 说明2:需要先操作redis存一下库存:set stock 1000
     * @return
     */
    @GetMapping("/lockTest")
    public String stock(){
        String lock_key = "lock";
        RLock lock = redisson.getLock(lock_key);//第一步，获取锁
        try {
            lock.lock();//第二步，加锁
            int stock = Integer.parseInt(template.opsForValue().get("stock"));
            if (stock>0) {
                template.boundValueOps("stock").increment(-1);
                log.info("库存扣减成功，剩余库存：{}",stock - 1);
            }else {
                log.info("库存扣减失败，库存不足");
            }
        } finally {
            lock.unlock();//第三步，释放锁
        }
        return "hi";
    }
}
